package cn.bocai.pc.web.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.bocai.pc.model.BcDrawing;
import cn.bocai.pc.model.BcLinktble;
import cn.bocai.pc.model.BcLinktype;
import cn.bocai.pc.service.BcCollectService;
import cn.bocai.pc.service.BcDrawCollectService;
import cn.bocai.pc.service.BcDrawingService;
import cn.bocai.pc.service.BcLinktbleService;
import cn.bocai.pc.service.BcLinktypeService;
import cn.bocai.pc.service.BcPictureService;
import cn.bocai.pc.service.BcThumpicService;
import cn.bocai.pc.service.VariableService;
import cn.bocai.pc.util.FMutil;


@Controller
@RequestMapping("/staticPage")
public class StaticController {
	@Autowired
	private BcThumpicService bcThumpicService;
	@Autowired
	private BcLinktbleService bcLinktbleService;
	@Autowired
	private BcLinktypeService bcLinktypeService;
	@Autowired
	private BcCollectService bcCollectService;
	@Autowired
	private BcPictureService bcPictureService;
	@Autowired
	private VariableService variableService;
	@Autowired
	private BcDrawingService bcDrawingService;
	@Autowired
	private BcDrawCollectService bcDrawCollectService;

	/*@RequestMapping("/toMenuIndex.do")
	public String toAddBrand(){
		return "menu/index";
	}*/
	/** 
	    * 生成静态页面
	  */ 
	@RequestMapping("/StaticHtml.do")
	public void StaticHtml(HttpServletRequest request, HttpServletResponse response,String type) throws IOException{
		String var="";
		/*String black="";*/
		if("home".equals(type)){//首页生成静态
			var=homePage(request,response);
		}else if("colBlack".equals(type)){//彩图黑白生成静态
			/*var=colBlackPage(request,response,"1");
			if("success".equals(var)){
			 var=colBlackPage(request,response,"0");
			}*/
			var = bcPictureService.colBlackPage("1");
			if("success".equals(var)){
				var=bcPictureService.colBlackPage("0");
				}
		}else if("draw".equals(type)){//全年图纸
			String year=variableService.selectVariable("year");
			var=drawPage(request,response,year);
			if("success".equals(var)){
				var=drawPage(request,response,String.valueOf(Integer.parseInt(year)+1));
			}
		}
		try {
			response.getWriter().print(var);
		} catch (IOException e) {
			e.printStackTrace();
		}
	} 
	//首页生成静态页面
	public String homePage(HttpServletRequest request, HttpServletResponse response){
		String PackPath = variableService.selectVariable("PACKGE_TEMPLATE");//模板地址
		String portUrl = variableService.selectVariable("port_url"); //D:/ruanjian/tomcat/apache-tomcat-7.0.26/wtpwebapps/pc-portal
		String variable=variableService.selectVariable("PIC_URL");
		String variableYear=variableService.selectVariable("year");//最新年份
		String staticYear=variableService.selectVariable("picStatic_Year");//图纸开始年份
		String porUrl=variableService.selectVariable("POR_URL");//静态页面磁盘映射
		
		//将年份转换为int类型
		int i=Integer.parseInt(staticYear);
		int n=Integer.parseInt(variableYear);
		 List<String> list=new ArrayList<String>();
	for (int year= i; year <= n;year++) {
			Collections.reverse(list);//强数据反转
			if(2012!=year){
				list.add(String.valueOf(year-1));
				Collections.reverse(list);//强数据反转
			}
		}
		
		
		Map<String,Object> allMap=new HashMap<String,Object>();
			 Map<String, Object> playMap = new HashMap<String,Object>();
			 playMap.put("year",variableYear);
			//查询首页轮播图的地址
			List<Map<String, Object>> playArrayList = bcThumpicService.getSelectRecommend(playMap);
			allMap.put("nextYear", String.valueOf(Integer.parseInt(variableYear)+1));
			allMap.put("url",variable);
			allMap.put("year",variableYear);
			allMap.put("moveList",playArrayList);
			allMap.put("porUrl",porUrl);
			allMap.put("yearList", list);// 年份集合
		//查询友情链接类型参数1表示类型
		List<BcLinktype> selectByFriendship = bcLinktypeService.selectByFriendship("1");
		List<Map<String, Object>> arrayList = new ArrayList<Map<String, Object>>();
		 for(BcLinktype tmp:selectByFriendship){
			 Map<String,Object> map=new HashMap<String,Object>();
			//通过类型id查询出对应的链接信息
			 List<BcLinktble> selectByLink = bcLinktbleService.selectByLink(tmp.getId());
			 map.put("LinkKey",tmp.getLinkTypename());
			 map.put("LinkVal",selectByLink);
			 arrayList.add(map);
	        }
		 allMap.put("arrayList",arrayList);
		 
		 String var="success";
			FMutil fMutil = new FMutil();
					//生成静态页面。如名称相同覆盖
					try {
						fMutil.ouputLinkFile("index.ftl","lookFour.html", allMap,"/index.html",PackPath,portUrl);
					} catch (Exception e) {
						var="erro";
						e.printStackTrace();
					}
		return var;
	}
	
	/*//生成彩色黑白静态页面
	public String colBlackPage(HttpServletRequest request, HttpServletResponse response,String colour){
		//到数据字典去查询出对的的值
			String PackPath = variableService.selectVariable("PACKGE_TEMPLATE");//模板地址
			String colAddress = variableService.selectVariable("ColPage_Address"); //D:/colHtml
			String blackAddress = variableService.selectVariable("BlackPage_Address"); //D:/blackHtml
			String porUrl=variableService.selectVariable("POR_URL");//静态页面磁盘映射 /static
			String variable=variableService.selectVariable("PIC_URL");//http://localhost:8081/static
			String variableYear=variableService.selectVariable("year");//最新年份
			String staticYear=variableService.selectVariable("picStatic_Year");//图纸开始年份
			String varHtmlUrl = variableService.selectVariable("HTML_URL");// /pc-portal
			
			//将年份转换为int类型
			int i=Integer.parseInt(staticYear);
			int n=Integer.parseInt(variableYear);
			 String var="success";//返回上层的判断值
			 List<String> list=new ArrayList<String>();
		for (int year= i; year <= n;year++) {
			Collections.reverse(list);//强数据反转
			if(2012!=year){
				list.add(String.valueOf(year-1));
				Collections.reverse(list);//强数据反转
			}
		 Map<String, Object> allMap = new HashMap<String, Object>();
			int searRowAll = bcThumpicService.searRowAll(colour);// 查询出总的行数
			String colous = "";
			String returnUrl = "";
			String typeName = "";
			String storeAddress="";
			if ("1".equals(colour)) {
				colous = "col";
				returnUrl = "/col/col.html";
				typeName = "彩色";
				 storeAddress=colAddress+"/"+year;
				if(n==year){
				 storeAddress=colAddress;
				}
			} else {
				colous = "black";
				returnUrl = "/black/black.html";
				typeName = "黑白";
				storeAddress=blackAddress+"/"+year;
				if(n==year){//当年份是当前最新年份的时候存放位置没有年份文件夹
				storeAddress=blackAddress;
				}
			}
			allMap.put("nextYear", String.valueOf(Integer.parseInt(variableYear)+1));
			allMap.put("yearList", list);// 年份集合
			allMap.put("typeName", typeName);// 中文类型名称
			allMap.put("porUrl", porUrl);
			allMap.put("url", variable);
			allMap.put("year", String.valueOf(year));
			allMap.put("colous", colous);
			allMap.put("bcUrl", varHtmlUrl);
			allMap.put("nowUrl",returnUrl);
			allMap.put("endRow", searRowAll);// 总行数
			Map<String, String> articleMap = new HashMap<String, String>();
			articleMap.put("year",String.valueOf(year));
			articleMap.put("colour", colour);
			List<Map<String, Object>> returnColOrBlack = bcPictureService
					.selectColOrBlack(articleMap);
			allMap.put("selectColOrBlack", returnColOrBlack);
			//监测文件夹是否存在，不存在就创建
			newFile(storeAddress);
			FMutil fMutil = new FMutil();
			// 生成静态页面。如名称相同覆盖
			try {
				fMutil.ouputLinkFile("colBlackPage.ftl", colous + ".html", allMap, "/"+ colous + ".html",PackPath,storeAddress);
			} catch (Exception e) {
				var = "erro";
				e.printStackTrace();
			}
		}
			return var;
		}*/

	// 全年图纸生成静态页面
	public String drawPage(HttpServletRequest request,HttpServletResponse response, String variableYear) {
		// 到数据字典去查询出对的的值
		String PackPath = variableService.selectVariable("PACKGE_TEMPLATE");// 模板地址
		String drawAddress = variableService.selectVariable("Drawing_Address"); // D:/drawingsHtml
		String nowYear = variableService.selectVariable("year");// 最新年份
		String staticYear = variableService.selectVariable("picStatic_Year");// 图纸开始年份
		String draUrl = variableService.selectVariable("DRA_UEL");// /drawPic
		String baUrl = variableService.selectVariable("BA_URL");// http://localhost:8081
		String var = "success";
		// 将年份转换为int类型
		int i = Integer.parseInt(staticYear);
		int n = Integer.parseInt(nowYear);
		List<String> list = new ArrayList<String>();
		for (int year = i; year <= n; year++) {
			Collections.reverse(list);// 强数据反转
			if (2012 != year) {
				list.add(String.valueOf(year - 1));
				Collections.reverse(list);// 强数据反转
			}
		}
		FMutil fMutil = new FMutil();
		Map<String, Object> allMap = new HashMap<String, Object>();
		allMap.put("year", nowYear);
		allMap.put("conYear", variableYear);
		allMap.put("nextYear",String.valueOf(Integer.parseInt(variableYear) + 1));
		allMap.put("yearList", list);// 年份集合
		allMap.put("draUrl", draUrl);
		allMap.put("baUrl", baUrl);
		
		//1:定义每页显示多少行记录
		int pageSize =1500;
		//默认等于第一页
		int currentPage = 1;
		//查询出一共多少条数
		int rowCount = bcDrawingService.searThumAllRowAll(variableYear);
		//4:计算一共分多少页
		int pageCount = rowCount/pageSize+(rowCount%pageSize==0?0:1);
		List<Integer> numberList=new ArrayList<Integer>();
		//将页码收集为一个数组进行返回前台
		for(int y=currentPage;y<=pageCount;y++){
			numberList.add(y);
		}
		allMap.put("numberList", numberList);//页码集合
		if(rowCount!=0){
		for(int x=currentPage;x<=pageCount;x++){
			int pageNumber=pageSize;
			
			allMap.put("nowNumber", x);//当前页面
			//5:计算从哪一行开始查询
			int start = (x-1)*pageSize;
			pageSize=pageSize*x;
			String drawHtml="draw"+x+".html";
			if(1==x){
				 drawHtml="draw.html";
			}
			//判断当前页面要求页数是否已经大于pageCount（总页数）最大页数，如果大于就拿总页数否则就拿页面要求的
			currentPage=(currentPage>pageCount?pageCount:currentPage);
			//判断
	     	currentPage=(currentPage<=0?1:currentPage);
	
			Map<String,Object> drawMap = new HashMap<String,Object>();
			drawMap.put("start",start);
			drawMap.put("pageSize",pageSize);
			drawMap.put("year",variableYear);
			List<BcDrawing> returnColOrBlack = bcDrawingService.selectPagingDraw(drawMap);
			/*//查询出不同分页的数据
			List<BcDrawing> returnColOrBlack= drawPaging(request,response,variableYear);*/
			allMap.put("drawGather", returnColOrBlack);
			
			String depositDraw=drawAddress;
			if (!variableYear.equals(nowYear)) {
				drawAddress = drawAddress + "/" + variableYear;
			}
			// 监测文件夹是否存在，不存在就创建
			newFile(drawAddress);
			// 生成静态页面。如名称相同覆盖
			try {
				fMutil.ouputLinkFile("drawing.ftl", drawHtml, allMap,"/"+drawHtml, PackPath, drawAddress);
				drawAddress=depositDraw;//将默认值赋值回去以免出现文件夹多层创建
				pageSize=pageNumber;
			} catch (Exception e) {
				var = "erro";
				e.printStackTrace();
			}
		}
		}else{
			
			List<BcDrawing> returnColOrBlack = bcDrawingService.selectAllDraw(variableYear);
			allMap.put("drawGather", returnColOrBlack);
			if (!variableYear.equals(nowYear)) {
				drawAddress = drawAddress + "/" + variableYear;
			}
			String drawHtml="draw.html";
			// 监测文件夹是否存在，不存在就创建
			newFile(drawAddress);
			try {
				fMutil.ouputLinkFile("drawing.ftl", drawHtml, allMap,"/"+drawHtml, PackPath, drawAddress);
			} catch (Exception e) {
				var = "erro";
				e.printStackTrace();
			}
		}
		return var;
	}

	// 判断文件夹是否存在，不存在就创建
	public void newFile(String filepath) {
		// 查找指定目录下的文件
		File file = new File(filepath);
		if (!file.exists() || !file.isDirectory()) {
			//System.out.println("目录不存在");
			file.mkdirs();// 不存在就创建 (可以创建多级目录)
		}
	}
}
